/**
 * 文件上传
 */
Fw.Upload = Fw.extend(Fw.Component, {
	contentEl: '',
	secureuri: true, //是否启用安全提交
	//上传
	uploadUrl: Fw.getBasePath()+'/channel/httpUpload.do',
	//下载
	downloadUrl: Fw.getBasePath()+'/channel/httpDownload.do',
	mulit: false, // 多文件上传
	dataType: 'json', //服务器返回的格式,可以是json或xml等,
	fileType: undefined, //支持上传文件类型,为空时不限制文件类型，（文件类型以,分隔。如'jpg,png,doc' 或 '.jpg,.png,.doc'）
	fileTypeText: undefined,
	view: false,//是否查看状态（不允许上传、删除）
	allowDownload: true,//允许下载
	allowPreview: true,//允许预览
	addIcon: 'glyph-plus', //选择文件按钮图标
	delIcon: 'glyph-minus',//删除按钮图标
	downloadIcon: 'glyph-chevron-down',//下载按钮图标
	/**
	 * 初始化组件
	 */
	initComponent: function(){
		this.id = Fw.id();
		Fw.Upload.superclass.initComponent.call(this);
		this.value = null;
		if(this.mulit){
			this.value = [];
		}
		if(!Fw.isEmpty(this.fileType)){
			var types = this.fileType.split(',');
			var reg = '/^.+(';
			Fw.each(types,function(t){
				if(!Fw.isEmpty(Fw.trim(t))){
					reg += '(\\.'+t+')|';
				}
			},this);
			if(reg.length>1){
				reg = reg.substring(0,reg.length-1);
				reg += ')$/i';
				this.regex = eval(reg);
			}
		}
		this.initFileinput();
	},
	initFileinput: function(){
		var html = '<i class="glyph '+this.addIcon+'"></i>';
		html+='<span>选择文件...</span>';
		html+='<input id="'+this.id+'" type="file" name="file">';
		this.fileinputEl.html(html);
		this.el = $('#'+this.id);
		this.el.on('change',Fw.bind(this.onChange, this));
	},
	initTpl: function(){
		var html = '<div class="file-btn-div" id="'+this.id+'-headDiv">';
		html+='<span class="btn btn-success fileinput-button" id="'+this.id+'-fileinput">';
		html+='</span>';
		if(this.mulit){
			html+='&nbsp;<button class="btn btn-danger" id="'+this.id+'-deleteAll">';
			html+='<i class="glyph '+this.delIcon+'"></i>';
			html+='<span>全部删除</span>';
			html+='</button>';
		}
		html+='</div>';
		html+='<div class="file-list-div">';
		html+='<table role="presentation" class="table table-striped" id="'+this.id+'-table">';
		html+='</table>';
		html+='</div>';
		$('#'+this.contentEl).html(html);
		this.fileinputEl = $('#'+this.id+'-fileinput');
		this.delAllEl = $('#'+this.id+'-deleteAll');
		this.tableEl = $('#'+this.id+'-table');
		this.headEl = $('#'+this.id+'-headDiv');
	},
	/**
	 * 初始化事件
	 */
	initEvents: function(){
		if(this.mulit){
			this.delAllEl.on('click',Fw.bind(this.deleteAll, this));
		}
	},
	onUpload: function(){
		var me = this;
		$.ajaxFileUpload({
			//处理文件上传操作的服务器端地址(可以传参数,已亲测可用)
			url: me.uploadUrl,
			//是否启用安全提交,默认为false
			secureuri: me.secureuri,
			//文件选择框的id属性
			fileElementId: me.id,
			//服务器返回的格式,可以是json或xml等 	
			dataType: me.dataType,
			success: function(r){me.onRequestSuccess(r);},
			error: function(status, textStatus, error){me.onRequestFailure(status, textStatus, error)}
		});
	},
	onChange: function(e) {
		var file = this.el.val();
		if(!Fw.isEmpty(file)){
			if(!Fw.isEmpty(this.fileType)){
				var fileName = file.substring(file.lastIndexOf('\\')+1, file.length);
				if(!this.regex.test(fileName)){
					var msg = Fw.isEmpty(this.fileTypeText)?'请上传 '+this.fileType+' 格式的文件':this.fileTypeText;
					Fw.Msg.warn(msg);
					return false;
				}
			}
			this.onUpload();
		}
	},
	onRequestSuccess: function(result) {
		try{
			var data;
			if(result){
				if(result['success'] !== true){
					this.onRequestFailure({}, {}, result['error'] || result['message']);
					return;
				}
				data = result['result'];
			} else {
				result = null;
				data = null;
			}
			
			var d = [data];
			if(this.mulit){
				this.value.push(data);
				d = this.value;
			} else {
				this.value = data;
			}
			this.showFileInfos(d);
			this.initFileinput();
			this.fireEvent('success', this, data, result, this.value);
		}catch (e){
			Fw.Msg.error('AJAX请求错误\n' + e);
		}
	},
	onRequestFailure: function(status, textStatus, error){
		var errorDetail = status.responseText;
        status = status.status;
        var allowErrorMsg = this.fireEvent('error', this, status, textStatus, error);
        //
        switch(status) {
            //登陆超时，拒绝访问
            case 401://'Unauthorized'
                Fw.Msg.warn('您的登录信息已经超时，请重新登录！', function(){
                	if(window.top){
                		window.top.location.href = Fw.getBasePath();
                	}else {
	                	location.href = Fw.getBasePath();
                	}
                });
                break;
            //服务器挂了
            case 0://'communication failure'
                Fw.Msg.error('访问服务器失败！<br>请检查您的网络连接是否正常或者与系统管理员联系。');
                break;
            //其他，抛异常
            default:
                if(allowErrorMsg !== false){
                    if(errorDetail){
                        Fw.Msg.show(
                            '错误',
                            'icon-error', 
                            '文件上传发生异常。<br>' + error, 
                            [
                                {id: 'ok', text: '确定', cls: 'btn-primary'},
                                {id: 'detail', text: '查看', cls: 'btn-danger'}
                            ],
                            function(type){
                                if(type === 'detail'){
                                    Fw.Window.show({
                                        title: '错误明细',
                                        html: errorDetail,
                                        buttons: [
                                            {text: '确定', cls: 'btn-primary'}
                                        ]
                                    });
                                }
                            }
                        );
                    }
                    else{
                        Fw.Msg.error('数据请求发生异常。<br>' + error);
                    }
                }
        }
	},
	/**
	 * 显示文件信息
	 */
	showFileInfos: function(data){
		var tpl = [
			'{@each data as item,index}',
				'{@if item.operation != "DELETE"}',
					'<tr id="${item.fileId}">',
					'<td>',
					'<span  class="fileName',
					this.allowPreview?' file-preview':'',
					'" tmp="${item.tmp}" fileType="${item.fileType}" title="${item.fileName}${item.fileType}">${item.fileName}${item.fileType}</span>',
					'</td>',
					'<td align="right"><span class="fileSize">${item.fileSize|fileSize}</span></td>',
					'<td width="170">',
						this.view?'':'<button class="btn btn-danger btn-sm delete-button"><i class="glyph '+this.delIcon+'"></i><span>删除</span></button>',
						'{@if item.tmp == false }',
							this.allowDownload?'&nbsp;<button class="btn btn-info btn-sm upload-button"><i class="glyph '+this.downloadIcon+'"></i><span>下载</span></button>':'',
						'{@/if}',
					'</td>',
					'</tr>',
				'{@/if}',
			'{@/each}'
		];
		this.tableEl.html(Fw.template(tpl,{
			data: data
		}));
		$('.file-preview').on('click',Fw.bind(this.onPreview, this));
		$('.delete-button').on('click',Fw.bind(this.onDel, this));
		$('.upload-button').on('click',Fw.bind(this.onDownload, this));
	},
	/**
     * 获取文件上传信息
     */
    getValue: function(){
    	return this.value;
    },
    /**
     * 回显已上传文件信息
     */
    setValue: function(v){
    	this.value = v;
    	if(Fw.isEmpty(v)){
    		this.clearValue();
    	} else {
    		var data = [];
    		if(this.mulit){
    			data = v;
    		} else {
    			data.push(v);
    		}
    		this.showFileInfos(data);
    	}
    },
    /**
     * 清空文件信息
     */
    clearValue: function(){
    	this.tableEl.empty();
    	if(this.mulit){
			this.value = [];
		} else {
			this.value = null;
		}
    },
	/**
     * 全部删除
     */
    deleteAll: function(){
		this.tableEl.empty();
    	if(this.mulit){
    		$.each(this.value, function(n,v){
				v.operation = 'DELETE';
			});
    	} else {
	    	this.value = null;
    	}
    },
    /**
     * 删除
     * @param {} e
     */
    onDel: function(e){
    	var fileId = $(e.currentTarget).parent().parent().attr('id');
    	$('#'+fileId).remove();
    	if(this.mulit){
	    	$.each(this.value, function(n,v){
				if(v.fileId == fileId){
					v.operation = 'DELETE';
					return false;
				}
			});
    	} else {
    		this.value = null;
    	}
    },
    /**
     * 预览
     * @param {} e
     */
    onPreview: function(e) {
    	var id = $(e.currentTarget).parent().parent().attr('id');
    	var tmp = $(e.currentTarget).attr('tmp');
    	var fileType = $(e.currentTarget).attr('fileType');
    	var url = this.downloadUrl + '?model=preview&fileId='+id+'&tmp='+tmp;
    	this.fireEvent('preview', this, id, url, fileType);
    },
    /**
     * 下载
     */
    onDownload: function(e){
    	var id = $(e.currentTarget).parent().parent().attr('id');
    	var url = this.downloadUrl + '?fileId='+id;
    	window.open(url);
    },
	/**
	 * 设置查看状态
	 * @param {} flag
	 */
	setView: function(flag){
    	if(!Fw.isBoolean(flag)) return;
    	this.view = flag;
    	if(flag){
			this.headEl.hide();
		} else {
			this.headEl.show();
		}
    	this.setValue(this.value);
    },
	/**
     * 设置允许下载
     */
    setAllowDownload: function(flag){
    	if(!Fw.isBoolean(flag)) return;
    	this.allowDownload = flag;
    	this.setValue(this.value);
    },
    /**
     * 设置允许预览
     * @param {} flag
     */
    setAllowPreview: function(flag){
    	if(!Fw.isBoolean(flag)) return;
    	this.allowPreview = flag;
    	this.setValue(this.value);
    },
	/**
	 * 完成渲染
	 */
	finishRender: function(){
		Fw.Upload.superclass.finishRender.call(this);
	}
});
//,
/*********************************************************************************************************/
// JavaScript Document
jQuery.extend({
	
	
	createUploadIframe : function(id, uri) {
		// create frame
		var frameId = 'jUploadFrame' + id;
		/**判断浏览器版本     开始*/
		var FR = {};
		//浏览器判断
		//是否IE
		FR.isIE = !!document.documentMode;
		$.each([7, 8, 9, 10, 11], function(n,v){
			FR['isIE' + v] = FR.isIE && document.documentMode === v;
		});
		
		/**判断浏览器版本     结束*/
		/*
		 * 新代码 开始
		 */
		if(!FR.isIE || FR['isIE11'] || FR['isIE10'] || FR['isIE9']){
			var io = document.createElement('iframe');   
	        io.id = frameId;   
	        io.name = frameId;  
		} else if(FR['isIE8'] || FR['isIE7']){
			var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');   
          	if(typeof uri== 'boolean'){   
            	io.src = 'javascript:false';   
          	} else if(typeof uri== 'string'){   
            	io.src = uri;   
          	}   
		}
		/*
		 * 新代码 结束
		 */
		/*
		 * 原代码 开始
		 */
//		if (window.ActiveXObject) {
//			var io = document.createElement('<iframe id="' + frameId
//					+ '" name="' + frameId + '" />');
//			if (typeof uri == 'boolean') {
//				io.src = 'javascript:false';
//			} else if (typeof uri == 'string') {
//				io.src = uri;
//			}
//		} else {
//			var io = document.createElement('iframe');
//			io.id = frameId;
//			io.name = frameId;
//		}
		/*
		 * 原代码 结束
		 */
		io.style.position = 'absolute';
		io.style.top = '-1000px';
		io.style.left = '-1000px';

		document.body.appendChild(io);

		return io;
	},
	createUploadForm : function(id, fileElementId) {
		// create form
		var formId = 'jUploadForm' + id;
		var fileId = 'jUploadFile' + id;
		var form = jQuery('<form  action="" method="POST" name="' + formId
				+ '" id="' + formId + '" enctype="multipart/form-data"></form>');
		var oldElement = jQuery('#' + fileElementId);
		var newElement = jQuery(oldElement).clone();
		jQuery(oldElement).attr('id', fileId);
		jQuery(oldElement).before(newElement);
		jQuery(oldElement).appendTo(form);
		// set attributes
		jQuery(form).css('position', 'absolute');
		jQuery(form).css('top', '-1200px');
		jQuery(form).css('left', '-1200px');
		jQuery(form).appendTo('body');
		return form;
	},

	ajaxFileUpload : function(s) {
		// TODO introduce global settings, allowing the client to modify them
		// for all requests, not only timeout
		s = jQuery.extend({}, jQuery.ajaxSettings, s);
		var id = s.fileElementId;
		var form = jQuery.createUploadForm(id, s.fileElementId);
		var io = jQuery.createUploadIframe(id, s.secureuri);
		var frameId = 'jUploadFrame' + id;
		var formId = 'jUploadForm' + id;

		if (s.global && !jQuery.active++) {
			// Watch for a new set of requests
			jQuery.event.trigger("ajaxStart");
		}
		var requestDone = false;
		// Create the request object
		var xml = {};
		if (s.global) {
			jQuery.event.trigger("ajaxSend", [xml, s]);
		}

		var uploadCallback = function(isTimeout) {
			// Wait for a response to come back
			var io = document.getElementById(frameId);
			try {
				if (io.contentWindow) {
					xml.responseText = io.contentWindow.document.body
							? io.contentWindow.document.body.innerHTML
							: null;
					xml.responseXML = io.contentWindow.document.XMLDocument
							? io.contentWindow.document.XMLDocument
							: io.contentWindow.document;

				} else if (io.contentDocument) {
					xml.responseText = io.contentDocument.document.body
							? io.contentDocument.document.body.innerHTML
							: null;
					xml.responseXML = io.contentDocument.document.XMLDocument
							? io.contentDocument.document.XMLDocument
							: io.contentDocument.document;
				}
			} catch (e) {
//				jQuery.handleError(s, xml, null, e);
				var text = xml.responseText;
				if(text == null || text == undefined || text == ''){
					xml = {};
					xml.status = 0;
				} else if(text.indexOf('401')>=0){
					xml.status = 401;
				}
				status = 'error';
				if(s.error){
					s.error(xml, xml, status);
				}
				return;
			}
			if (xml || isTimeout == "timeout") {
				requestDone = true;
				var status;
				try {
					status = isTimeout != "timeout" ? "success" : "error";
					// Make sure that the request was successful or notmodified
					if (status != "error") {
						// process the data (runs the xml through httpData
						// regardless of callback)
						var data = jQuery.uploadHttpData(xml, s.dataType);
						if (s.success) {
							// ifa local callback was specified, fire it and
							// pass it the data
							s.success(data, status);
						};
						if (s.global) {
							// Fire the global callback
							jQuery.event.trigger("ajaxSuccess", [xml, s]);
						};
					} else {
//						jQuery.handleError(s, xml, status, e);
						var text = xml.responseText;
						if(text == null || text == undefined || text == ''){
							xml = {};
							xml.status = 0;
						} else if(text.indexOf('401')>=0){
							xml.status = 401;
						}
						status = 'error';
						if(s.error){
							s.error(xml, xml, status);
						}
						return;
					}

				} catch (e) {
//					jQuery.handleError(s, xml, status, e);
					var text = xml.responseText;
					if(text == null || text == undefined || text == ''){
						xml = {};
						xml.status = 0;
					} else if(text.indexOf('401')>=0){
						xml.status = 401;
					}
					status = 'error';
					if(s.error){
						s.error(xml, xml, status);
					}
					return;
				};
				if (s.global) {
					// The request was completed
					jQuery.event.trigger("ajaxComplete", [xml, s]);
				};

				// Handle the global AJAX counter
				if (s.global && !--jQuery.active) {
					jQuery.event.trigger("ajaxStop");
				};
				if (s.complete) {
					s.complete(xml, status);
				};

				jQuery(io).unbind();

				setTimeout(function() {
							try {
								jQuery(io).remove();
								jQuery(form).remove();

							} catch (e) {
//								jQuery.handleError(s, xml, null, e);
								var text = xml.responseText;
								if(text == null || text == undefined || text == ''){
									xml = {};
									xml.status = 0;
								} else if(text.indexOf('401')>=0){
									xml.status = 401;
								}
								status = 'error';
								if(s.error){
									s.error(xml, xml, status);
								}
								return;
							}

						}, 100);

				xml = null;

			};
		}
		// Timeout checker
		if (s.timeout > 0) {
			setTimeout(function() {

						if (!requestDone) {
							// Check to see ifthe request is still happening
							uploadCallback("timeout");
						}

					}, s.timeout);
		}
		try {
			var form = jQuery('#' + formId);
			jQuery(form).attr('action', s.url);
			jQuery(form).attr('method', 'POST');
			jQuery(form).attr('target', frameId);
			if (form.encoding) {
				form.encoding = 'multipart/form-data';
			} else {
				form.enctype = 'multipart/form-data';
			}
			jQuery(form).submit();

		} catch (e) {
//			jQuery.handleError(s, xml, null, e);
			var text = xml.responseText;
			if(text == null || text == undefined || text == ''){
				xml = {};
				xml.status = 0;
			} else if(text.indexOf('401')>=0){
				xml.status = 401;
			}
			status = 'error';
			if(s.error){
				s.error(xml, xml, status);
			}
			return;
		}
		if (window.attachEvent) {
			document.getElementById(frameId).attachEvent('onload',
					uploadCallback);
		} else {
			document.getElementById(frameId).addEventListener('load',
					uploadCallback, false);
		}
		return {
			abort : function() {
			}
		};

	},

	uploadHttpData : function(r, type) {
		var data = !type;
		data = type == "xml" || data ? r.responseXML : r.responseText;
		// ifthe type is "script", eval it in global context
		if (type == "script") {
			jQuery.globalEval(data);
		}
		// Get the JavaScript object, ifJSON is used.
		if (type == "json") {
			data = data.replace(/<[^>]+>/g,"");
			eval("data = " + data);
			//data = $.parseJSON(data);
		}
		// evaluate scripts within html
		if (type == "html") {
			jQuery("<div>").html(data).evalScripts();
		}
		return data;
	}
});
/*********************************************************************************************************/